package cn.hwadee.muying.controller;


import cn.hwadee.muying.commons.utils.FormUtils;
import cn.hwadee.muying.commons.utils.SendMail;
import cn.hwadee.muying.dto.Client;
import cn.hwadee.muying.entity.Organization;
import cn.hwadee.muying.entity.User;
import cn.hwadee.muying.service.OrganizationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import cn.hwadee.muying.commons.base.BaseController;
import cn.hwadee.muying.commons.jqgrid.GridResult;
import cn.hwadee.muying.commons.page.MyPage;
import org.springframework.ui.Model;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.hwadee.muying.service.CareRecordService;
import cn.hwadee.muying.entity.CareRecord;

import java.sql.Timestamp;
import java.util.*;

import org.apache.shiro.authz.annotation.Logical;
import cn.hwadee.muying.service.ClientService;
/**
* <p>
* 关怀记录 前端控制器
*
* </p>
*
* @author SuWuqiang
* @since 2018-08-08
*/
@Controller
@RequestMapping("/sys/careRecord")
public class CareRecordController extends BaseController {
    @Autowired
    private CareRecordService careRecordService;

    @Autowired
    private ClientService clientService;

    @Autowired
    private OrganizationService organizationService;

    @ModelAttribute("careRecord")
    public CareRecord get(@RequestParam(required = false)Long id) throws Exception{
        if(id != null && id > 0){
            return careRecordService.selectById(id);
        }else{
            return new CareRecord();
        }
    }

    @RequiresPermissions("sys:careRecord:list")
    @RequestMapping(value="/list",produces = "text/html;charset=utf-8",method = RequestMethod.GET)
    public String list(Model model) throws Exception{
        return "/biz/careRecord/list";
    }

    @ResponseBody
    @RequiresPermissions("sys:careRecord:list")
    @RequestMapping(value="/list.json",produces = "application/json;charset=utf-8")
    public GridResult list(Timestamp start, Timestamp end, String keyword) throws Exception{
        //System.out.println(start+"  end:"+end);
        MyPage<CareRecord> page = getPage();
        page = careRecordService.list(page,getCurrentUser(),start,end,keyword);
        GridResult result = new GridResult(page.getCurrent(),page.getPages(),page.getCurrent(),page.getRecords());
        return result;
    }

    @RequiresPermissions("sys:careRecord:send")
    @RequestMapping(value="/send",produces = "text/html;charset=utf-8",method = RequestMethod.GET)
    public String send(Model model) throws Exception{
        return "/biz/careRecord/send";
    }

    @ResponseBody
    @RequiresPermissions("sys:careRecord:send")
    @RequestMapping(value="/send.json",produces = "application/json;charset=utf-8")
    public GridResult send(Boolean old,String keyword) throws Exception{
        MyPage<Client> page = getPage();
        page = careRecordService.send(page,getCurrentUser(),old, keyword);
        GridResult result = new GridResult(page.getCurrent(),page.getPages(),page.getCurrent(),page.getRecords());
        return result;
    }

    /**
     * 跳转添加/编辑关怀记录界面
     * @param careRecord
     * @param model
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value={"sys:careRecord:edit","sys:careRecord:add"},logical=Logical.OR)
    @RequestMapping(value = {"/edit","/add"}, produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String add(@ModelAttribute CareRecord careRecord,Model model,String ids) throws Exception{
        model.addAttribute("careRecord",careRecord);
        model.addAttribute("ids",ids);
        if(ids != null && !ids.equals("")){
            List<Long> idsArray = Arrays.asList(FormUtils.getIdsArray(ids));
            model.addAttribute("number",idsArray.size());
            if(idsArray.size() > 0){
                Client client = clientService.selectById(idsArray.get(0));
                model.addAttribute("firstClientName",client.getUsername());
            }else {
                model.addAttribute("firstClientName",null);
            }
        }
        return "/biz/careRecord/edit";
    }

    /**
     * 处理更新关怀记录的请求
     * @param careRecord
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value={"sys:careRecord:edit","sys:careRecord:add"},logical=Logical.OR)
    @RequestMapping(value = "/edit", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(@ModelAttribute CareRecord careRecord,String ids,String content){
        Map<String,Object> result = new HashMap();
        //int success = 0, fail = 0;
        try {
        if(careRecord.getId() != null && careRecord.getId() > 0){
            careRecordService.updateById(careRecord);
        }else {
            //careRecordService.insert(careRecord);
            String organization = organizationService.selectById(getCurrentUser().getOrgId()).getName();
            if(ids != null && !ids.equals("")){
                List<Long> idsArray = Arrays.asList(FormUtils.getIdsArray(ids));
                /*ArrayList<Boolean> answer = new ArrayList<>();
                ArrayList<Long> userIds = new ArrayList<>();
                for(Long id : idsArray) {
                    Client client = clientService.selectById(id);
                    userIds.add(client.getUserId());
                    if (SendMail.sendMail(client.getEmail(), organization, content)) {
                        success++;
                        answer.add(true);
                    } else {
                        fail++;
                        answer.add(false);
                    }
                }
                careRecord.setContent(content);
                careRecord.setOrgId(getCurrentUser().getOrgId());
                careRecord.setWorkerId(getCurrentUser().getId());
                careRecord.setWay("email");
                for(int i = 0; i < idsArray.size(); i++){
                    careRecord.setReceiveId(userIds.get(i));
                    careRecord.setStatus(answer.get(i));
                    careRecordService.insert(careRecord);
                }*/
                Long orgID = getCurrentUser().getOrgId();
                Long workerId = getCurrentUser().getId();
                for(Long id : idsArray){
                    new Thread(){
                        @Override
                        public void run(){
                            Client client = clientService.selectById(id);
                            CareRecord careRecordThread = new CareRecord();
                            careRecordThread.setContent(content);
                            careRecordThread.setOrgId(orgID);
                            careRecordThread.setWorkerId(workerId);
                            careRecordThread.setWay("email");
                            careRecordThread.setReceiveId(client.getUserId());
                            careRecordThread.setStatus(SendMail.sendMail(client.getEmail(), organization, content));
                            careRecordService.insert(careRecordThread);
                        }
                    }.start();
                }
            }
        }
        //result.put("success",success);
        //result.put("fail",fail);
        result.put("status",200);
        result.put("msg","关怀记录信息保存成功");
        }catch (Exception e){
        e.printStackTrace();
        result.put("status",500);
        result.put("msg","关怀记录信息保存失败");
        }
        return result;
    }

    /**
     * 处理删除关怀记录的请求
     * @param id
     * @return
     * @throws Exception
     */
    @RequiresPermissions("sys:careRecord:delete")
    @RequestMapping(value = "/delete", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> delete(Long id){
        Map<String,Object> result = new HashMap();
        try {
        if(id != null && id > 0){
            careRecordService.deleteById(id);
            result.put("status",200);
            result.put("msg","删除关怀记录成功");
        }else {
            result.put("status",500);
            result.put("msg","请选择删除的关怀记录");
        }
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","删除关怀记录失败");
        }
        return result;
    }

}
